package com.lin.gameserver;

import com.lin.gameserver.handler.MessageDispatcher;
import com.lin.gameserver.session.SessionManager;
import com.lin.gameserver.websocket.GameWebSocketEndpoint;
import org.glassfish.tyrus.server.Server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import jakarta.websocket.DeploymentException;
import java.util.Scanner;

/**
 * 游戏服务器应用入口
 */
public class GameServerApplication {
    private static final Logger logger = LoggerFactory.getLogger(GameServerApplication.class);
    
    // WebSocket服务器
    private static Server server;
    
    // 默认配置
    private static final String DEFAULT_HOST = "0.0.0.0";
    private static final int DEFAULT_PORT = 9010;
    private static final String DEFAULT_CONTEXT_PATH = "/";
    
    public static void main(String[] args) {
        try {
            // 启动服务器
            startServer();
            
            // 等待控制台输入，用于优雅关闭
            waitForExit();
            
        } catch (Exception e) {
            logger.error("服务器启动失败: {}", e.getMessage(), e);
        }
    }
    
    /**
     * 启动WebSocket服务器
     *
     * @throws DeploymentException 部署异常
     */
    private static void startServer() throws DeploymentException {
        // 创建服务器
        server = new Server(DEFAULT_HOST, DEFAULT_PORT, DEFAULT_CONTEXT_PATH,
                null, GameWebSocketEndpoint.class);
        
        // 启动服务器
        server.start();
        
        logger.info("游戏服务器已启动: ws://{}:{}{}", 
                DEFAULT_HOST.equals("0.0.0.0") ? "localhost" : DEFAULT_HOST, 
                DEFAULT_PORT, 
                DEFAULT_CONTEXT_PATH);
    }
    
    /**
     * 等待退出命令
     */
    private static void waitForExit() {
        logger.info("输入 'exit' 以关闭服务器...");
        
        try (Scanner scanner = new Scanner(System.in)) {
            while (true) {
                String line = scanner.nextLine();
                if ("exit".equalsIgnoreCase(line.trim())) {
                    logger.info("接收到退出命令，正在关闭服务器...");
                    stopServer();
                    break;
                }
            }
        }
    }
    
    /**
     * 停止服务器
     */
    private static void stopServer() {
        try {
            // 关闭消息分发器
            MessageDispatcher.getInstance().shutdown();
            
            // 关闭会话管理器
            SessionManager.getInstance().shutdown();
            
            // 停止WebSocket服务器
            if (server != null) {
                server.stop();
                logger.info("WebSocket服务器已停止");
            }
            
            logger.info("游戏服务器已成功关闭");
        } catch (Exception e) {
            logger.error("关闭服务器时发生错误: {}", e.getMessage(), e);
        }
    }
} 